import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Spin, message } from 'antd';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { ApiOutlined, UserOutlined, ClockCircleOutlined, AlertOutlined } from '@ant-design/icons';
import { getApiStatistics } from '../../services/api';
import './Dashboard.css';

const Dashboard = () => {
  const [loading, setLoading] = useState(true);
  const [statistics, setStatistics] = useState({
    totalApi: 0,
    activeApi: 0,
    totalUsers: 0,
    todayRequests: 0,
  });
  const [apiMethodData, setApiMethodData] = useState([]);
  const [apiStatusData, setApiStatusData] = useState([]);

  // 模拟数据 - 用于演示
  const mockApiMethodData = [
    { name: 'GET', value: 65 },
    { name: 'POST', value: 45 },
    { name: 'PUT', value: 20 },
    { name: 'DELETE', value: 15 },
    { name: '其他', value: 10 },
  ];

  const mockApiStatusData = [
    { name: '正常', value: 85, color: '#52c41a' },
    { name: '异常', value: 15, color: '#ff4d4f' },
  ];

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8'];

  useEffect(() => {
    // 获取统计数据
    const fetchStatistics = async () => {
      try {
        setLoading(true);
        const response = await getApiStatistics();
        if (response.code === 200) {
          setStatistics(response.data);
          // 实际项目中应该使用后端返回的数据
          // 这里为了演示，使用模拟数据
          setApiMethodData(mockApiMethodData);
          setApiStatusData(mockApiStatusData);
        }
      } catch (error) {
        message.error('获取统计数据失败');
        console.error('获取统计数据失败:', error);
        // 出错时使用模拟数据
        setApiMethodData(mockApiMethodData);
        setApiStatusData(mockApiStatusData);
      } finally {
        setLoading(false);
      }
    };

    fetchStatistics();
    // 每30秒刷新一次数据
    const interval = setInterval(fetchStatistics, 30000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div className="dashboard-container">
      <h2>仪表盘</h2>
      
      <Spin spinning={loading} tip="加载中...">
        {/* 统计卡片行 */}
        <Row gutter={16} className="dashboard-stats">
          <Col span={6}>
            <Card>
              <Statistic
                title="API总数"
                value={statistics.totalApi || 120}
                prefix={<ApiOutlined />}
                suffix="个"
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="活跃API"
                value={statistics.activeApi || 95}
                prefix={<ClockCircleOutlined />}
                suffix="个"
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="用户总数"
                value={statistics.totalUsers || 50}
                prefix={<UserOutlined />}
                suffix="人"
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="今日请求数"
                value={statistics.todayRequests || 1250}
                prefix={<AlertOutlined />}
                suffix="次"
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 图表行 */}
        <Row gutter={16} className="dashboard-charts">
          <Col span={12}>
            <Card title="API方法分布" className="chart-card">
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={apiMethodData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="value" fill="#8884d8" />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="API状态分布" className="chart-card">
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={apiStatusData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  >
                    {apiStatusData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default Dashboard;